package com.tiancikeji.zaoke.app.dao.food.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.tiancikeji.zaoke.app.dao.food.FoodNutritionDao;
import com.tiancikeji.zaoke.app.model.food.FoodNutrition;
import com.tiancikeji.zaoke.app.model.food.Nutrition;

public class FoodNutritionDaoImpl extends JdbcDaoSupport implements FoodNutritionDao{

	private static final String TABLE = " from `zaoke`.`food_nutrition` as `fn` left join `zaoke`.`nutrition` as `nu` on `fn`.`nutrition_id` = `nu`.`id`";
	private static final String QUERY_VIEW = "`nu`.`name` as `nutrition_name`, `fn`.`id` as `id`, `fn`.`food_id` as `food_id`, `fn`.`nutrition_id` as `nutrition_id`, `fn`.`value` as `value`, `fn`.`add_userid` as `add_userid`, `fn`.`add_time` as `add_time`, `fn`.`lastmod_userid` as `lastmod_userid`, `fn`.`lastmod_time` as `lastmod_time`";

	private List<FoodNutrition> _query(String sql) {
		List<FoodNutrition> tags = getJdbcTemplate().query(sql, new RowMapper<FoodNutrition>() {

			public FoodNutrition mapRow(ResultSet rs, int rowNum) throws SQLException {
				FoodNutrition nutrition = new FoodNutrition();
				nutrition.setId(rs.getLong("id"));
				nutrition.setFoodid(rs.getLong("food_id"));
				Nutrition nut = new Nutrition();
				nut.setId(rs.getLong("nutrition_id"));
				nut.setName(rs.getString("nutrition_name"));
				nutrition.setNutrition(nut);
				nutrition.setValue(rs.getString("value"));
				nutrition.setAddUserid(rs.getLong("add_userid"));
				nutrition.setAddTime(rs.getDate("add_time"));
				nutrition.setLastmodUserid(rs.getLong("lastmod_userid"));
				nutrition.setLastmodTime(rs.getDate("lastmod_time"));
				return nutrition;
			}
		});
		return tags;
	}

	public List<FoodNutrition> getNutritionsByFoodIds(Set<Long> remainings) {
		String sql = "select " + QUERY_VIEW + TABLE + " where `fn`.`food_id` in (";
		sql += StringUtils.join(remainings, ",");
		sql += ")";
		return _query(sql);
	}

	public List<FoodNutrition> getAllNutritions() {
		String sql = "select " + QUERY_VIEW + TABLE;
		return _query(sql);
	}
}
